package com.example.booktest.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.booktest.entity.CatalogEntity;
import com.example.booktest.retrofit.RetrofitClient;
import com.example.booktest.service.GoodBookService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class CatalogViewModel extends ViewModel {
    private final GoodBookService service;
    private final CompositeDisposable disposable = new CompositeDisposable();
    private final MutableLiveData<CatalogEntity> catalogData = new MutableLiveData<>();

    public CatalogViewModel() {
        service = RetrofitClient.getClient().create(GoodBookService.class);
    }

    public void getGoodBooks(String apiKey) {
        Disposable disposable = service.getGoodBooks(apiKey, "json")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this.catalogData::postValue, this::handleError);
        this.disposable.add(disposable);
    }

    public LiveData<CatalogEntity> getCatalogData() {
        return catalogData;
    }

    private void handleError(Throwable throwable) {
        // Handle error, e.g., show a message
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        disposable.dispose();
    }
}